<?php

class SessionSaveHandlerMysql implements SessionSaveHandler {
	static $maxLifeTime = 1440;
	static $tablename = '';
	private $handler;
	function __construct($settings,$options){
		if(!function_exists('mysql_connect')){
			trigger_error('Mysql Session Init failed Class Not Exist.', E_USER_ERROR);
			return false;
		}
		if(empty($settings) || empty($settings['mysql']['servers'])){
			trigger_error('Mysql Session Init failed Settings Empty.', E_USER_ERROR);
			return false;
		}
		is_array($options) && isset($options['gc_maxlifetime']) && self::$maxLifeTime = $options['gc_maxlifetime'];
		self::$tablename = $settings['mysql']['tablename'];
		$connectFunc = 'mysql_connect';
		if(isset($settings['mysql']['pconnect']) && $settings['mysql']['pconnect']==TRUE){
			$connectFunc = 'mysql_pconnect';

		}
		//@todo support multi server
		$link = $connectFunc($settings['mysql']['servers'][0]['host'],$settings['mysql']['servers'][0]['username'],$settings['mysql']['servers'][0]['password']);
		if(!$link){
			trigger_error('Mysql Session Init failed Connect Failed.', E_USER_ERROR);
			return false;
		}
		if(!@mysql_select_db($settings['mysql']['servers'][0]['dbname'], $link)){
			trigger_error('Mysql Session Init failed select db Failed.'.mysql_errno($link).mysql_error($link), E_USER_ERROR);
			return false;
		}

		if(isset($settings['mysql']['charset'])){
			if(!@mysql_query("SET NAMES '".$settings['mysql']['charset']."'",$link)){
				trigger_error('Mysql Session Init failed set chartset error.'.mysql_errno($link).mysql_error($link), E_USER_ERROR);
				return false;
			}
		}
		if(isset($settings['mysql']['checkinstall']) && $settings['mysql']['checkinstall']==TRUE){
			if(!@mysql_query("DESCRIBE ".self::$tablename,$link)){
				if(mysql_errno($link)==1146){
					// create table
					$crsql = "CREATE TABLE IF NOT EXISTS `".self::$tablename."` ( `sess_id` char(32) NOT NULL,  `sess_expires` int(10) unsigned NOT NULL default '0',  `sess_data` varchar(10000) NOT NULL, PRIMARY KEY  (`sess_id`),  KEY `sess_expires` (`sess_expires`)) ENGINE=MEMORY DEFAULT CHARSET=".(isset($settings['mysql']['charset'])?$settings['mysql']['charset']:'utf8').";";
					if(!@mysql_query($crsql,$link)){
						trigger_error('Mysql Session Init failed create table error.'.mysql_errno($link).mysql_error($link), E_USER_ERROR);
						return false;
					}
				}else{
					trigger_error('Mysql Session Init failed get dbtable error.'.mysql_errno($link).mysql_error($link), E_USER_ERROR);
					return false;
				}
			}
		}
		$this->handler = $link;
	}
    function open($save_path, $session_name){
        return true;
    }

    function close(){
        return true;
    }

    function read($session_id){
    	$res = mysql_query("SELECT `sess_data` FROM `".self::$tablename."` WHERE `sess_id` = '".mysql_escape_string($session_id)."'");
    	if(mysql_num_rows($res) != 0){
    		return mysql_result($res,0);
    	}else{
    		return '';
    	}
    }

    function write($session_id, $session_data){
    	if(@mysql_query("INSERT INTO `".self::$tablename."` (`sess_id`, `sess_expires`, `sess_data`) VALUES ('".mysql_escape_string($session_id)."','".(time()+self::$maxLifeTime)."','".mysql_escape_string($session_data)."' )",$this->handler)){
    		return true;
    	}else{
    		return mysql_query("REPLACE INTO `".self::$tablename."` (`sess_id`, `sess_expires`, `sess_data`) VALUES ('".mysql_escape_string($session_id)."','".(time()+self::$maxLifeTime)."','".mysql_escape_string($session_data)."' )",$this->handler);
    	}
    }

    function destroy($session_id){
		return mysql_query("DELETE FROM `".self::$tablename."` WHERE `sess_expires`  `sess_id` = '".mysql_escape_string($session_id)."'",$this->handler);
    }

    function gc($maxlifetime=0){
       return mysql_query("DELETE FROM `".self::$tablename."` WHERE `sess_expires`  < ".time(),$this->handler);
    }
}
?>